package com.fy.fyspace.common.interceptor;

import com.fy.fyspace.service.impl.MonitorServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 监控拦截器
 * 用于统计API调用次数和错误次数
 */
@Slf4j
@Component
public class MonitorInterceptor implements HandlerInterceptor {

    @Resource
    private MonitorServiceImpl monitorService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 增加API调用计数
        monitorService.incrementApiCallCount();
        
        // 记录请求信息
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        log.debug("API调用: {} {}", method, requestURI);
        
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 如果有异常，增加错误计数
        if (ex != null) {
            monitorService.incrementErrorCount();
            log.error("API调用异常: {} {} - {}", request.getMethod(), request.getRequestURI(), ex.getMessage());
        }
    }
} 